package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.sign.SignBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.sign.back.CheckSignBack;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.sign.vo.CheckSignForm;
import com.cloudbroker.bcs.platform.dav.middle.model.ParamEncrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Map;

/**
 * Created by wangxu13798 on 2016/11/24.
 */
@Service
public class SignBizServiceImpl implements SignBizService {
    @Override
    public CheckSignBack funcCheckSign(CheckSignForm param) {
        // FIXME: 2016/11/24 可以想更好的方式来管理加密串
        Map<String,String> encryptKeyMap = new HashMap<>();
        encryptKeyMap.put("getOpenid","a1234567");
        encryptKeyMap.put("registe","abc12345");
        if(StringUtil.isEmpty(encryptKeyMap.get(param.getSign_type()))){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.ENCRYPT_TYPE_ERROR,CheckSignBack.class);
        }
        CheckSignBack back = new CheckSignBack();
        ParamEncrypt encrypt = new ParamEncrypt();
        JSONObject encryptObj;
        JSONObject waitEncryptObj;
        try {
            encryptObj = JSON.parseObject(param.getEncrypt_str());
            waitEncryptObj = JSON.parseObject(param.getWait_encrypt_str());
        }catch (Exception e){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.REQUEST_PARA_ERROR,CheckSignBack.class);
        }
        for(Entry<String,Object> entry : encryptObj.entrySet()){
            encrypt.putParam(entry.getKey(), ValueUtil.getString(entry.getValue()));
        }
        encrypt.putParam("encryptKey",encryptKeyMap.get(param.getSign_type()));
        encrypt.setSign(param.getSign());
        if(!encrypt.checkSign()){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.CHECK_SIGN_FAIL,CheckSignBack.class);
        }
        ParamEncrypt waitEncrypt = new ParamEncrypt();
        for(Entry<String,Object> entry : waitEncryptObj.entrySet()){
            waitEncrypt.putParam(entry.getKey(), ValueUtil.getString(entry.getValue()));
        }
        waitEncrypt.putParam("encryptKey",encryptKeyMap.get(param.getSign_type()));
        back.setSign(waitEncrypt.sign());
        return VOUtil.setSuccessResult(back);
    }
}
